<template>
  <div>
    <n-card>
      <n-form-item
        path="name"
        label-placement="left"
        style="display: flex; justify-content: space-between; margin-bottom: 10px"
      >
        <n-button type="info" @click="add" style="margin-right: 20px">新增</n-button>
        <n-button type="error" @click="alldele" style="margin-right: 20px">批量删除</n-button>
        <n-input
          type="text"
          placeholder="请输入姓名"
          style="width: 200px; float: right; margin-right: 20px"
          v-model:value="array.search"
        />
        <n-button type="info" @click="search" style="margin-right: 20px">搜索</n-button>
        <n-button style="margin-right: 20px" type="warning" @click="reset">重置</n-button>
        <n-button type="success" @click="importexcel">导出</n-button>
      </n-form-item>
      <n-data-table
        :data="array.data"
        :columns="columns"
        :pagination="pagination"
        :row-key="rowKey"
        @update:checked-row-keys="handleCheck"
        scroll-x="800"
      ></n-data-table>
    </n-card>
    <!-- 新增弹窗 -->
    <n-modal
      v-model:show="array.add"
      :mask-closable="false"
      preset="dialog"
      title="新增"
      style="position: relative"
    >
      <n-form
        label-placement="left"
        label-width="auto"
        :rules="addrules"
        ref="formRef"
        :model="model"
      >
        <n-form-item label="岗位" path="jobs">
          <n-input v-model:value="model.jobs" placeholder="请输入岗位名称" />
        </n-form-item>
        <n-form-item label="岗位介绍" path="info">
          <n-input
            v-model:value="model.info"
            placeholder="请输入岗位介绍"
            type="textarea"
            maxlength="90"
            show-count
          />
        </n-form-item>
        <n-form-item label="人数" path="number">
          <n-input-number v-model:value="model.number" />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
            type="info"
            style="position: absolute; right: 3%"
          >
            保存
          </n-button>
        </n-form-item>
      </n-form>
    </n-modal>
    <!-- 编辑弹窗 -->
    <n-modal
      v-model:show="array.edite"
      :mask-closable="false"
      preset="dialog"
      title="编辑"
      style="position: relative"
    >
      <n-form
        label-placement="left"
        label-width="auto"
        :rules="addrules"
        ref="formRef"
        :model="model1"
      >
        <n-form-item label="岗位" path="jobs">
          <n-input v-model:value="model1.jobs" placeholder="请输入岗位名称" />
        </n-form-item>
        <n-form-item label="岗位介绍" path="info">
          <n-input
            v-model:value="model1.info"
            placeholder="请输入岗位介绍"
            type="textarea"
            maxlength="90"
            show-count
          />
        </n-form-item>
        <n-form-item label="人数" path="number">
          <n-input-number v-model:value="model1.number" />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick1"
            type="info"
            style="position: absolute; right: 3%"
          >
            保存修改
          </n-button>
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<script>
  import { h, reactive, ref, defineComponent, getCurrentInstance } from 'vue';
  import { NButton, useMessage, useDialog } from 'naive-ui';
  import * as XLSX from 'xlsx';
  import table2excel from 'js-table2excel';
  const createColumns = ({ edite, dele }) => {
    return [
      {
        type: 'selection',
        disabled(row) {
          return row.name === 'Edward King 3';
        },
      },
      {
        title: 'id',
        key: 'id',
      },
      {
        title: '岗位',
        key: 'jobs',
      },
      {
        title: '岗位介绍',
        key: 'info',
      },
      {
        title: '招聘人数',
        key: 'number',
      },
      {
        title: '操作',
        key: 'actions',
        fixed: 'right',
        width: 60,
        titleRowSpan: 2,
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'info',
              onClick: () => edite(row),
            },
            { default: () => '编辑' }
          );
        },
      },
      {
        title: '',
        width: 60,
        fixed: 'right',
        key: 'dele',
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => dele(row),
            },
            { default: () => '删除' }
          );
        },
      },
    ];
  };

  export default defineComponent({
    setup() {
      const formRef = ref(null);
      const checkedRowKeysRef = ref([]);
      const message = useMessage();
      const dialog = useDialog();
      let { proxy } = getCurrentInstance();
      const array = reactive({
        data: [],
        add: false,
        edite: false,
        alldele: [],
        search: '',
        data1: [],
        tabledata: [],
        alldata: [],
      });
      const model = reactive({
        jobs: null,
        info: null,
        number: null,
      });
      const model1 = reactive({});
      function load() {
        proxy
          .$axios({
            url: '/api/recruit/index/index',
            method: 'post',
            data: {
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res);
            console.log(res.data.data.list);
            array.data = res.data.data.list;
            array.alldata = res.data.data.list;
          });
      }
      load();
      const paginationReactive = reactive({
        page: 1,
        pageSize: 5,
        showSizePicker: true,
        pageSizes: [3, 5, 7],
        onChange: (page) => {
          paginationReactive.page = page;
        },
        onUpdatePageSize: (pageSize) => {
          paginationReactive.pageSize = pageSize;
          paginationReactive.page = 1;
        },
      });

      const add = () => {
        array.add = true;
      };
      function alldele() {
        if (array.alldele.length == 0) {
          message.error('您未选取删除项');
        } else {
          dialog.warning({
            title: '提示',
            content: '确定要删除这些招聘信息吗？',
            positiveText: '确定',
            negativeText: '不确定',
            onPositiveClick: () => {
              proxy
                .$axios({
                  url: '/api/recruit/index/del',
                  method: 'post',
                  data: {
                    id: array.alldele,
                    admin_id: 111,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.code == 1) {
                    message.success('删除成功');
                    load();
                  } else {
                    message.error('删除失败');
                  }
                });
            },
            onNegativeClick: () => {},
          });
        }
      }
      function search() {
        console.log(array.search);
        array.data1 = [];
        for (let i = 0; i < array.alldata.length; i++) {
          if (array.alldata[i].jobs.indexOf(array.search) != -1) {
            array.data1.push(array.alldata[i]);
          }
        }
        array.data = array.data1;
      }
      function reset() {
        array.search = '';
        load();
      }
      function importexcel() {
        let excelName = '招聘列表';
        let column = [
          {
            title: 'id',
            key: 'id',
          },
          {
            title: '岗位',
            key: 'jobs',
          },
          {
            title: '岗位介绍',
            key: 'info',
          },
          {
            title: '招聘人数',
            key: 'number',
          },
        ];
        if (array.tabledata.length == 0) {
          message.error('您未选中导出项');
        } else {
          table2excel(column, array.tabledata, excelName);
          message.success('导出成功');
          array.tabledata = [];
        }
      }
      return {
        importexcel,
        reset,
        search,
        array,
        alldele,
        formRef,
        addrules: {
          jobs: {
            required: true,
            message: '请输入岗位名称',
            trigger: ['blur', 'input'],
          },
          info: {
            required: true,
            message: '请输入岗位介绍',
            trigger: ['blur', 'input'],
          },
          number: {
            type: 'number',
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入招聘人数',
          },
        },
        handleValidateClick(e) {
          e.preventDefault();
          formRef.value?.validate((errors) => {
            if (!errors) {
              message.success('保存成功');
              // console.log(model.jobs);
              proxy
                .$axios({
                  url: '/api/recruit/index/add',
                  method: 'post',
                  data: {
                    jobs: model.jobs,
                    info: model.info,
                    number: model.number,
                    admin_id: 111,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res.data);
                  array.add = false;
                  model.jobs = null;
                  model.info = null;
                  model.number = null;
                  load();
                });
            } else {
              console.log(errors);
              message.error('请填写完整再提交');
            }
          });
        },
        handleValidateClick1(e) {
          e.preventDefault();
          formRef.value?.validate((errors) => {
            if (!errors) {
              console.log(model1);
              proxy
                .$axios({
                  url: '/api/recruit/index/edit',
                  method: 'post',
                  data: {
                    id: model1.id,
                    jobs: model1.jobs,
                    info: model1.info,
                    number: model1.number,
                    admin_id: 111,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res);
                  1;
                  if (res.data.code == 1) {
                    message.success('修改成功');
                    load();
                    array.edite = false;
                  } else {
                    message.error('保存失败');
                    array.edite = false;
                  }
                });
            } else {
              console.log(errors);
              message.error('请填写完整再提交');
            }
          });
        },
        add,
        model,
        model1,
        // 删除、编辑
        columns: createColumns({
          edite(rowData) {
            array.edite = true;
            console.log(model1);
            console.log(rowData);
            model1.jobs = rowData.jobs;
            model1.info = rowData.info;
            model1.number = rowData.number;
            model1.id = rowData.id;
          },
          dele(rowData) {
            console.log(rowData.id);
            dialog.warning({
              title: '提示',
              content: '确定要删除这条招聘信息吗？',
              positiveText: '确定',
              negativeText: '不确定',
              onPositiveClick: () => {
                proxy
                  .$axios({
                    url: '/api/recruit/index/del',
                    method: 'post',
                    data: {
                      id: rowData.id,
                      admin_id: 111,
                      admin_name: '张',
                    },
                  })
                  .then((res) => {
                    console.log(res);
                    if (res.data.code == 1) {
                      message.success('删除成功');
                      load();
                    } else {
                      message.error('删除失败');
                    }
                  });
              },
              onNegativeClick: () => {},
            });
          },
        }),
        pagination: paginationReactive,
        checkedRowKeys: checkedRowKeysRef,
        rowKey: (row) => row,
        handleCheck(rowKeys) {
          console.log(rowKeys);
          for (let i = 0; i < rowKeys.length; i++) {
            array.alldele.push(rowKeys[i].id);
          }
          array.tabledata = rowKeys;
        },
        handleUploadChange(e) {
          console.log(e);
          var reader = new FileReader();
          reader.onload = function (e) {
            var data = e.target.result;
            // 读取二进制的excel
            var workbook = XLSX.read(data, { type: 'binary' });
            if (callback) callback(workbook);
          };
          reader.readAsBinaryString(e.file);
          console.log(reader);
        },
      };
    },
  });
</script>

<style scoped lang="less">
  .top {
    height: 30px;
    width: 80px;
    background-color: #2080f0;
    font-size: 14px;
    line-height: 30px;
    cursor: pointer;
    display: inline-block;
    text-align: center;
    color: #fff;
    border-radius: 3px;
    margin-right: 20px;
  }
  .top:hover {
    background-color: #4098fc;
  }
</style>
